'''
Created on 01/03/2013

@author: Elfi
'''
#from twisted.python import log
from twisted.web import http, proxy
from twisted.python import log
from metrics.http_statistics import GlobalHttpMetrics
from proxy.web_resource import WebResource
import time, sys
from storage.db_connection import DBConnection

class CacheProxyClient(proxy.ProxyClient):
    """Manage returned header, content here.

    Use `self.father` methods to modify request directly.
    """
    
    def connectionMade(self):
        log.msg("Connection made")
        self.__web_resource = WebResource()
    
        GlobalHttpMetrics.getInstance().httpRequests += 1
        self.__web_resource.timeElapsed = time.clock()
        proxy.ProxyClient.connectionMade(self)
    
    def handleStatus(self, version, code, message):
        GlobalHttpMetrics.getInstance().statusCount(code)
        self.__web_resource.status = code
        proxy.ProxyClient.handleStatus(self, version, code, message)
    
    def handleHeader(self, key, value):
        # change response header here
        #log.msg("URL: %s -- %s" % (self.headers["host"], self.rest) )
        log.msg("Header CacheProxyClient: %s: %s" % (key, value))
        if ( key == "Content-Length"):
            GlobalHttpMetrics.getInstance().totalTransfer += int(value)
            self.__web_resource.contentLength = int(value)
        elif key == "Content-Type":
            self.__web_resource.contentType = value
        self.__web_resource.addHeader(key,value)
        
        proxy.ProxyClient.handleHeader(self, key, value)

    def handleResponsePart(self, buf):
        # Store resource content
        self.__web_resource.addContent(buf)
        proxy.ProxyClient.handleResponsePart(self, buf)
        
    def handleResponseEnd(self):

        '''Preventing request close connection error '''
        try:
            proxy.ProxyClient.handleResponseEnd(self)
        except:
            pass
            
        self.__web_resource.timeElapsed = time.clock() - self.__web_resource.timeElapsed
        url = str(self.father)
        url = url[5:]
        url = url[:url.find(' ')]
        self.__web_resource.url = url
        GlobalHttpMetrics.getInstance().siteResponseTime(url,self.__web_resource.contentType, self.__web_resource.status, self.__web_resource.timeElapsed,self.__web_resource.contentLength)
        
        '''Store the object in the cache'''
        DBConnection.getInstance().cacheObject(self.__web_resource)        


class CacheProxyClientFactory(proxy.ProxyClientFactory):
    protocol = CacheProxyClient

class CacheProxyRequest(proxy.ProxyRequest):
    protocols = dict(http=CacheProxyClientFactory)

class CacheProxy(proxy.Proxy):
    requestFactory = CacheProxyRequest

class CacheProxyFactory(http.HTTPFactory):
    protocol = CacheProxy

